#include"mystdio.h"




myFILE* my_fopen(const char *path, const char *flag)
{
  int iscreate=0;
  int flags=0;
  mode_t mode=0666;
  if(strcmp(flag,"w")==0)
  {
    iscreate=1;
    flags=(O_WRONLY|O_CREAT|O_TRUNC);
  }
  else if(strcmp(flag,"r")==0)
  {
    flags=O_RDONLY;
  }
  else if(strcmp(flag,"a")==0)
  {
    iscreate=1;
    flags=O_WRONLY|O_CREAT|O_APPEND;

  }
  else 
  {}
  
  //打开或者创建文件
  int fd=0;
  if(iscreate)
    fd=open(path,flags,mode);
  else 
    fd=open(path,flags);
  if(fd<0)return NULL;
  myFILE*p=(myFILE*)malloc(sizeof(myFILE));
  p->fileno=fd;
  p->flags=FLUSH_LINE;
  p->pos=0;
  p->cap=LINE_SIZE;
  return p;
}


void my_fflush(myFILE *fp)
{
  write(fp->fileno,fp->cache,strlen(fp->cache));
  fp->pos=0;
}


ssize_t my_fwrite(myFILE *fp, const char *data, int len)
{
  memcpy(fp->cache+fp->pos,data,len);
  fp->pos+=len;
  if((fp->flags&FLUSH_LINE)||fp->cache[fp->pos-1]=='\n')
  {
    my_fflush(fp);
  }
  return len;
}

void my_fclose(myFILE *fp)
{
  my_fflush(fp);
  close(fp->fileno);
  free(fp);
}
